package v1

import (
	"fmt"
	"io/ioutil"
	"usplatformserver/global"
	"usplatformserver/internal/model"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type ReportTemplate struct{}

type reportInfo struct {
	TemplateInfo *model.ReportTemplateInfo
	Err          error
}

func NewReportTemplate() ReportTemplate {
	return ReportTemplate{}
}

// @Summer 获取报告模板
// @Produce json
// @Param token header string true "token"
// @Success 200 {object} model.ReportTemplateSwaggerInfo "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/report/template [get]
func (r *ReportTemplate) GetReportTemplate(c *gin.Context) {
	getChan := make(chan reportInfo, 1)
	svc := service.New(c.Request.Context())

	go func() {

		addr := fmt.Sprintf("tcp://%v:%d", global.ZMQSettings.Addr, global.ZMQSettings.Port)

		var info reportInfo
		reports, err := svc.GetReportTemplate(addr)
		info.TemplateInfo = reports
		info.Err = err
		getChan <- info
	}()

	for {
		info := <-getChan
		if info.Err != nil {
			global.Logger.Infof("svc.GetReportTemplate failed: %v", info.Err)
			response := app.NewResponse(c)
			response.ToErrorResponse(errcode.ErrorGetReportTemplateFail)
			break
		} else {
			response := app.NewResponse(c)
			response.ToResponse(info.TemplateInfo)
			break
		}
	}
	close(getChan)
}

// @Summer 设置报告模板
// @Produce json
// @Param token header string true "token"
// @Param reports body model.ReportTemplateInfo true "报告模板"
// @Success 200 {object} model.SwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/report/template [post]
func (r *ReportTemplate) SetReportTemplate(c *gin.Context) {
	getChan := make(chan error, 1)

	go func() {

		addr := fmt.Sprintf("tcp://%v:%d", global.ZMQSettings.Addr, global.ZMQSettings.Port)

		svc := service.New(c.Request.Context())
		//获取请求体
		reqBody, _ := ioutil.ReadAll(c.Request.Body)
		fmt.Println("SetReportTemplate reqBody: ", reqBody)

		err := svc.SetReportTemplate(addr, string(reqBody))
		getChan <- err
	}()
	for {
		err := <-getChan
		if err != nil {
			response := app.NewResponse(c)
			global.Logger.Infof("svc.SetReportTemplate failed: %v", err)
			response.ToErrorResponse(errcode.ErrorSetReportTemplateFail)
			break
		} else {
			response := app.NewResponse(c)
			response.ToResponseSuccess()
			break
		}
	}
	close(getChan)
}
